package cn.fan.minio.web;


import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


@RestController
@RequestMapping("/sku")
@Slf4j
public class SkuController {
    private String folder = "image";

    @Autowired
    private FileManager fileManager;


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/fileUpload")
    @ResponseBody
    public String uploadSkuImage(@RequestParam("fileName") MultipartFile file) {
        return fileManager.uploadFile(file);
    }

    @GetMapping(value = "/down")
    @ResponseBody
    public void downSkuImage(@RequestParam("filePath") String filePath, HttpServletResponse response) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        InputStream inputStream = fileManager.downLoad(filePath, response);
        String[] split = filePath.split("/");
        String filename = split[split.length - 1];
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        IOUtils.copy(inputStream, response.getOutputStream());
    }

    /**
     * 文件删除
     *
     * @param fileName
     * @return
     */
    @PostMapping(value = "/fileDelete")
    @ResponseBody
    public String deleteSkuImage(@RequestParam("fileName") String fileName) {
        fileManager.delete(fileName);
        return "true";
    }

}
